/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.googlecode.jsimplemarket.wicket.pages;

import com.googlecode.jsimplemarket.model.Creanta;
import com.googlecode.jsimplemarket.model.Firma;
import com.googlecode.jsimplemarket.model.Inchiriere;
import com.googlecode.jsimplemarket.model.Plata;
import com.googlecode.jsimplemarket.model.SpatiuComercial;
import com.googlecode.jsimplemarket.model.Taxa;
import com.googlecode.jsimplemarket.repository.GenericOrder;
import com.googlecode.jsimplemarket.repository.GenericProperty;
import com.googlecode.jsimplemarket.repository.GenericRestriction;
import com.googlecode.jsimplemarket.repository.GenericRestriction.Op;
import com.googlecode.jsimplemarket.service.GenericService;
import com.googlecode.jsimplemarket.service.InchiriereService;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

/**
 *
 * @author Alexandru.Codescu
 */
public class IstoricPlatiPage extends DefaultViewPage {
    @SpringBean(name = "genericService")
    private GenericService<SpatiuComercial> spatiuComercialService;
    @SpringBean(name = "genericService")
    private GenericService<Firma> firmaService;
    @SpringBean(name = "genericService")
    private GenericService<Inchiriere> inchiriereService;
    @SpringBean(name = "inchiriereService")
    private InchiriereService serviceInchiriere;
    @SpringBean(name = "genericService")
    private GenericService<Creanta> serviceCreanta;
    @SpringBean(name = "genericService")
    private GenericService<Plata> servicePlata;
    
    public String printStandardDate(Date data) {
		return new SimpleDateFormat("dd.MM.yyyy HH:mm").format(data);
	}
    
    private Locale locale = new Locale("ro","RO");
    private NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
    
    public class JavascriptEventConfirmation extends AttributeModifier {
        public JavascriptEventConfirmation(String event, String msg) {
            super(event, new Model(msg));
        }
     
        protected String newValue(final String currentValue, final String replacementValue) {
            String prefix = "var conf = confirm('" + replacementValue + "'); " +
                "if (!conf) return false; ";
            String result = prefix;
            if (currentValue != null) {
                result = prefix + currentValue;
            }
            return result;
        }
    }
    
    public IstoricPlatiPage(final Long idSpatiuComercial) {
        SpatiuComercial spatiuComercial = spatiuComercialService.getById(SpatiuComercial.class, idSpatiuComercial);
        final Label lblTaraba = new Label("lblTaraba", spatiuComercial.getCod());
        add(lblTaraba);
        
        Link lnkPrev = new Link("lnkPrev") {
            @Override
            public void onClick() {
            	if (idSpatiuComercial != 1) {
            		setResponsePage(new IstoricPlatiPage(idSpatiuComercial-1));
            	}                
            }
        };
    	
        Link lnkNext = new Link("lnkNext") {
            @Override
            public void onClick() {
            	if (idSpatiuComercial != 140) {
            		setResponsePage(new IstoricPlatiPage(idSpatiuComercial+1));
            	}
            }
        };
        add(lnkPrev, lnkNext);
        
        Object[] sc = serviceInchiriere.queryFirmaByTaraba(idSpatiuComercial,new Date());
    	final Long firmaId = (sc == null ? (1L) : (Long) sc[3]);    	
    	Firma firma1 = firmaService.getById(Firma.class, firmaId);
    	
    	GenericRestriction rstrTaxeZilnice = new GenericRestriction(
                new GenericProperty("creanta").setReference(
                new GenericProperty("taxa").setReference(
        		new GenericProperty("tipTaxa").setReference(
                new GenericProperty("id")))), 1L, Op.EQ
            );
    	GenericRestriction rstrTaxePeriodice = new GenericRestriction(
                new GenericProperty("creanta").setReference(
                new GenericProperty("taxa").setReference(
        		new GenericProperty("tipTaxa").setReference(
                new GenericProperty("id")))), 1L, Op.GT
            );
    	GenericRestriction rstrTaraba = new GenericRestriction(
                new GenericProperty("spatiuComercial").setReference(
                new GenericProperty("id")), idSpatiuComercial);
    	
    	GenericOrder ordTax = new GenericOrder(new GenericProperty("dataInceput"), false);
    	
    	List<Inchiriere> inchirieriTaxeZilnice = inchiriereService.getList(Inchiriere.class, Arrays.asList(rstrTaxeZilnice,rstrTaraba), Arrays.asList(ordTax));
    	List<Inchiriere> inchirieriTaxePeriodice = inchiriereService.getList(Inchiriere.class, Arrays.asList(rstrTaxePeriodice,rstrTaraba), Arrays.asList(ordTax));
    	
    	IstoricInchirieriView istoricTaxeZilnice = new IstoricInchirieriView("istoricTaxeZilnice", inchirieriTaxeZilnice);
    	IstoricInchirieriView istoricTaxePeriodice = new IstoricInchirieriView("istoricTaxePeriodice", inchirieriTaxePeriodice);
    	
        add(istoricTaxeZilnice,istoricTaxePeriodice);
    }
    
    private class IstoricInchirieriView extends ListView<Inchiriere> {

        public IstoricInchirieriView(String id, List<Inchiriere> inchirieri) {
            super(id, inchirieri);
        }
        
        @Override
        protected void populateItem(ListItem<Inchiriere> li) {
            final Inchiriere inchiriere = li.getModelObject();
            final Firma firma = firmaService.getById(Firma.class, (inchiriere.getFirma() == null) ? 1L : inchiriere.getFirma().getId());
            
            int index = li.getIndex() + 1;
            li.add(new Label("index", index + ""));
//            li.add(new Label("data", printStandardDate(inchiriere.getDataInceput())));
            li.add(new Label("data", DateFormat.getDateInstance(DateFormat.SHORT, locale).format(inchiriere.getDataInceput())));
            li.add(new Label("firma", (inchiriere.getFirma() == null) ? "---" : inchiriere.getFirma().getDenumire()));
            
            BigDecimal incasari = BigDecimal.ZERO;
            for (Taxa taxa : inchiriere.getTaxe()) {
                incasari = incasari.add(taxa.getValoare());
            }
            li.add(new Label("valoare", incasari.toString()));
            
            WebMarkupContainer editLink = new WebMarkupContainer("editLink");
            editLink.add(new AttributeAppender("data-target", "#M" + inchiriere.getId()));
            editLink.add(new Label("textLink", "edit"));
            li.add(editLink);
            
//            Firma firma = firmaService.getById(Firma.class, 1L);
            final DropDownChoice<Firma> ddcFirma = new DropDownChoice<Firma>(
                    "firma", 
//                    new PropertyModel<Firma>(this, "firma"),
                    new CompoundPropertyModel<Firma>(firma),
                    new LoadableDetachableModel<List<Firma>>() {
                        @Override
                        protected List<Firma> load() {
                        	List<GenericOrder> firmaOrder = new ArrayList<GenericOrder>();
                        	firmaOrder.add(new GenericOrder(new GenericProperty("denumire"), true));                        	
                            return firmaService.getList(Firma.class, null, firmaOrder);
                        }
                    }, 
                    new ChoiceRenderer<Firma>("denumire", "id")
            );
            
            final Link delLink = new Link("delLink") {
                @Override
                public void onClick() {

                    Inchiriere inchiriereDel = inchiriereService.getById(Inchiriere.class, inchiriere.getId());
                    Creanta creanta = inchiriereDel.getCreanta();
                    List<Plata> plati = creanta.getPlati();
                    for (Plata plata : plati) {
                        servicePlata.delete(plata);
                    }
                    serviceCreanta.delete(creanta);
                    inchiriereService.delete(inchiriereDel);                   
                    setResponsePage(new IstoricPlatiPage(inchiriere.getSpatiuComercial().getId()));
                }
            };
            
            delLink.add(new JavascriptEventConfirmation("onclick", "Sigur vrei sa stergi inregistrarea?"));
            
            li.add(delLink);
            
            WebMarkupContainer divModal = new WebMarkupContainer("divModal");
            divModal.add(new AttributeAppender("id", "M" + inchiriere.getId()));
       
            Form<?> form1 = new Form<Void>("form1");
            
            form1.add(new Label("lblOcupant", (inchiriere.getFirma() == null) ? "---" : inchiriere.getFirma().getDenumire()));
            form1.add(ddcFirma);
            form1.add(new SubmitLink("submit1") {
            	@Override
                	public void onSubmit() {
            			//Firma selected = firma1;
	            		inchiriere.setFirma(ddcFirma.getModelObject());
	            		inchiriereService.update(inchiriere);
	            		setResponsePage(new IstoricPlatiPage(inchiriere.getSpatiuComercial().getId()));
            	}
            });
            divModal.add(form1);
            li.add(divModal);
        }
        
    }
}
